function safeEval(expression, context = {}) {
    if (!isValidSyntax(expression)) {
        console.error("Syntax error: Invalid JavaScript expression");
        return null;
    }

    const recursionTracker = new Map();
    const maxRecursionDepth = 1000;
    const maxExecutionTime = 1000;
    
    try {
        const func = new Function('__context', '__tracker', '__maxDepth', `
            const originalSetTimeout = setTimeout;
            const originalSetInterval = setInterval;
            const originalSetImmediate = setImmediate;

            setTimeout = function() { throw new Error('Asynchronous functions are not allowed'); };
            setInterval = function() { throw new Error('Asynchronous functions are not allowed'); };
            setImmediate = function() { throw new Error('Asynchronous functions are not allowed'); };

            function trackCall(funcName, fn) {
                return function() {
                    const callStack = new Error().stack;
                    const callId = funcName + ':' + callStack.split('\n')[2];
                    
                    if (!__tracker.has(callId)) {
                        __tracker.set(callId, 0);
                    }
                    
                    const depth = __tracker.get(callId) + 1;
                    if (depth > __maxDepth) {
                        throw new Error('Infinite recursion detected in ' + funcName);
                    }
                    
                    __tracker.set(callId, depth);
                    try {
                        return fn.apply(this, arguments);
                    } finally {
                        __tracker.set(callId, depth - 1);
                    }
                };
            }

            const context = { ...__context };
            for (const key in context) {
                if (typeof context[key] === 'function') {
                    context[key] = trackCall(key, context[key]);
                }
            }

            const startTime = Date.now();

            function checkTimeout() {
                if (Date.now() - startTime > 1000) {
                    throw new Error('Execution timeout: Possible infinite loop');
                }
            }

            const originalForEach = Array.prototype.forEach;
            Array.prototype.forEach = function(callback, thisArg) {
                checkTimeout();
                return originalForEach.call(this, callback, thisArg);
            };
            
            const originalMap = Array.prototype.map;
            Array.prototype.map = function(callback, thisArg) {
                checkTimeout();
                return originalMap.call(this, callback, thisArg);
            };

            try {
                return eval('with(context) { ' + expression + ' }');
            } finally {
                setTimeout = originalSetTimeout;
                setInterval = originalSetInterval;
                setImmediate = originalSetImmediate;
                Array.prototype.forEach = originalForEach;
                Array.prototype.map = originalMap;
            }
        `);

        return new Promise((resolve, reject) => {
            const timeoutId = setTimeout(() => {
                reject(new Error('Execution timeout: Possible infinite loop'));
            }, maxExecutionTime);
            
            try {
                const result = func(context, recursionTracker, maxRecursionDepth);
                clearTimeout(timeoutId);
                resolve(result);
            } catch (error) {
                clearTimeout(timeoutId);
                reject(error);
            }
        });
    } catch (error) {
        console.error("Failed to run script: ", error);
        return Promise.reject(error);
    }
}

function isValidSyntax(expression) {
    if (!expression || typeof expression !== 'string') {
        return false;
    }

    const forbiddenPatterns = [
        /\bwhile\s*\(\s*true\s*\)/i,  // while(true)
        /\bfor\s*\(\s*;;\s*\)/i,      // for(;;)
        /\bFunction\s*\(/i,           // 动态创建函数
        /\beval\s*\(/i,               // eval
        /\brequire\s*\(/i,            // require
        /\bprocess\b/i,               // process
        /\bglobal\b/i,                // global
        /\bsetTimeout\b/i,            // setTimeout
        /\bsetInterval\b/i,           // setInterval
    ];
    
    for (const pattern of forbiddenPatterns) {
        if (pattern.test(expression)) {
            return false;
        }
    }

    try {
        new Function(`return ${expression}`);
        return true;
    } catch (error) {
        return false;
    }
}

/*
safeEval("1 + 2 * 3")
    .then(result => console.log("Result: ", result))
    .catch(error => console.error("Error: ", error));

safeEval("let i = 0; while(i < 1000000) { i++; } return i;")
    .then(result => console.log("Loop result: ", result))
    .catch(error => console.error("Loop error: ", error));

const recursiveContext = {
    factorial: function(n) {
        if (n <= 1) return 1;
        return n * this.factorial(n - 1);
    }
};

safeEval("factorial(10)", recursiveContext)
    .then(result => console.log("Recursion result: ", result))
    .catch(error => console.error("Recursion error: ", error));

const infiniteRecursiveContext = {
    infinite: function() {
        return this.infinite();
    }
};

safeEval("infinite()", infiniteRecursiveContext)
    .then(result => console.log("Should not reach here: ", result))
    .catch(error => console.error("Infinite recursion detected: ", error.message));
*/